<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <el-form style="margin-bottom: 10px" size="small" label-width="120px" ref="orderForm" :rules="rules"
               :model="crud.order"
               >
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="业务日期">
              <el-date-picker
                v-model="crud.order.busDate"
                type="date"
                :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                style="width: 100%;"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据编号">
              <el-input  :disabled="true" v-model="crud.order.code" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同名称" prop="name">
              <el-input :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" v-model="crud.order.name" placeholder="请输入合同名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="费用类型" prop="type">
              <el-select :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" v-model="crud.order.type" class="filter-item" clearable placeholder="请选择合同类型" size="small"
                         style="width: 100%;">
                <el-option
                  v-for="item in dict.t_fee_order_type"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" label="供应商" prop="supplierId">
              <zSelect :clearable="true" :value.sync="crud.order.supplierId==0?null:crud.order.supplierId"
                       :showName="crud.order.supplierName"
                       url="api/dropDown/basCustomerList"
                       :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                       :params="{isContact:'1,2'}"
                       style="width:  100%"
                       @change="changeSupplier"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" label="客户" prop="customerId">
              <zSelect :clearable="true" :value.sync="crud.order.customerId==0?null:crud.order.customerId"
                       :showName="crud.order.customerName"
                       :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                       url="api/dropDown/basCustomerList"
                       :params="{isContact:'0,2'}"
                       style="width:  100%"
                       @change="changeCustomer"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item  label="费用金额" prop="feeAmount">
              <el-input-number
                :disabled="true"
                style="width:100%"
                v-model="crud.order.feeAmount"
                :precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="供应商费用" prop="supplierAmount">
              <el-input-number
                :disabled="true"
                style="width:100%"
                v-model="crud.order.supplierAmount"
                :precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="自理费用" prop="ownAmount">
              <el-input-number
                :disabled="true"
                style="width:100%"
                v-model="crud.order.ownAmount"
                :precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="供应商比例" prop="ownAmount">
              <el-input-number
                :disabled="true"
                :max="100"
                style="width:100%"
                v-model="crud.order.supplierRate"
                :precision="2"
                :step="0.1"
                @change=""
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="自理比例" prop="ownAmount">
              <el-input-number
                :disabled="true"
                :max="100"
                style="width:100%"
                v-model="crud.order.ownRate"
                :precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="生效开始时间" prop="startDate">
              <el-date-picker
                v-model="crud.order.startDate"
                type="date"
                :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                style="width: 100%;"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="生效截止时间" prop="endDate">
              <el-date-picker
                v-model="crud.order.endDate"
                type="date"
                style="width: 100%;"
                :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否红冲">
              <el-select :disabled="crud.order.id" v-model="crud.order.isRed" class="edit-input" placeholder="请选择">
                <el-option
                  v-for="(item,index) in dict.common_yes_or_no"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="费用结算方式">
              <el-select  class="edit-input" v-model="crud.order.settleType" placeholder="请选择">
                <el-option
                  v-for="(item,index) in settleTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" >
            <el-form-item label="备注">
              <el-input v-model="crud.order.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin-bottom: 10px">
        <el-button slot="right" class="filter-item"
                   :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" size="mini"
                   type="primary" @click="addRow()">
          新增
        </el-button>
        <el-button slot="right" class="filter-item"
                   size="mini"
                   type="primary" @click="copyOrder">
          复制
        </el-button>
        <el-button slot="right" class="filter-item"
                   size="mini"
                   type="primary" @click="submit()">
          保存
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="success"
                   :disabled="crud.order.orderStatus !== 'SAVE'"
                   :loading="crud.passLoading" @click="crud.doDetailPassOrReject('PASS',id)">
          审核
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
                   :disabled="crud.order.orderStatus !== 'PASS'" @click="crud.doDetailPassOrReject('REJECT',id)">
          反审
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="success" :loading="crud.rejectLoading"
                   :disabled="crud.order.orderStatus !== 'PASS' || crud.order.type == 1" @click="doPay('pay',crud.order.type,id)">
          支付
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
                   :disabled="crud.order.orderStatus !== 'PASS' || crud.order.type == 2" @click="doPay('back',crud.order.type,id)">
          收回
        </el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
          :disabled="$route.params.id == 'add'"
        >打印
        </el-button>
        <el-button
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          :disabled="$route.params.id == 'add'"
        >打印预览
        </el-button>
      </div>
      <!--表格渲染-->
      <el-table ref="table" stripe border v-loading="crud.loading" :data="crud.order.detailList" size="small"
                style="width: 100%;"
                @selection-change="selectionHandler">
        <el-table-column type="selection" width="55"/>
        <el-table-column width="180" v-if="columns.visible('inStartDate')" prop="inStartDate" label="费用开始时间">
          <template slot-scope="{row}">
            <el-date-picker
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              v-model="row.inStartDate"
              type="date"
              style="width: 100%;"
              format="yyyy - MM - dd "
              value-format="yyyy-MM-dd"
              default-value
              placeholder="选择日期">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column width="180" v-if="columns.visible('useEndDate')" prop="useEndDate" label="费用截至时间">
          <template slot-scope="{row}">
            <el-date-picker
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              v-model="row.useEndDate"
              type="date"
              style="width: 100%;"
              format="yyyy - MM - dd "
              value-format="yyyy-MM-dd"
              default-value
              placeholder="选择日期">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('subjectCode')" prop="subjectCode" label="费用编码"/>
        <el-table-column width="160" v-if="columns.visible('subjectId')" prop="subjectId" label="费用名称">
          <template slot-scope="{row}">
            <el-select-tree
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              placeholder="请选择内容"
              :filterable="true"
              :data="subjects"
              v-model="row.subjectId"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              @node-click="changeSubjects($event,row)"
            ></el-select-tree>
          </template>
        </el-table-column>
        <el-table-column width="180" v-if="columns.visible('goodsBrandName')" prop="goodsBrandName" label="品牌">
          <template slot-scope="{row}">
            <zSelect :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                     :value.sync="row.goodsBrandId" :showName="row.goodsBrandName" :label="row.goodsBrandName"
                     placeholder="请选择品牌" url="api/dropDown/basGoodsBrandList" @change="changeBrand(row, $event)">
            </zSelect>
          </template>
        </el-table-column>
        <el-table-column width="180"  v-if="crud.order.settleType === 2" prop="goodsBrandName" label="商品">
          <template slot-scope="{row}">
            <jtg-select-plus ref="productRef"
                             v-model="row.goodsId"
                             :initValue="row.goodsName"
                             typeName="SALE"
                             :customerId="crud.order.customerId"
                             @change="changeGoods($event,row)"
                             url="productList"/>
          </template>
        </el-table-column>
        <el-table-column   v-if="crud.order.settleType === 2" prop="taxPrice" label="含税单价" width="150" >
          <template slot-scope="scope">
            <el-input :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                      @input.native="crud.inuptCount(scope, 'taxPrice',taxAmountChangeFeeAmount)"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      v-model.lazy="scope.row.taxPrice"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column  v-if="crud.order.settleType === 2"  prop="taxBoxPrice" label="含税箱价" width="150">
          <template slot-scope="scope">

            <el-input :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                      @input.native="crud.inuptCount(scope, 'taxBoxPrice',taxAmountChangeFeeAmount)"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      v-model.lazy="scope.row.taxBoxPrice"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column width="250" v-if="crud.order.settleType === 2" prop="taxPrice" label="辅数量" >
          <template slot-scope="scope">
            <span v-if="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'">{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
            <el-input v-else
                      @input.native="crud.inuptCount(scope, 'boxNum',taxAmountChangeFeeAmount)"
                      v-model="scope.row.boxNum"
                      style="width: 45%!important;">
              <template slot="append" >{{scope.row.boxUnitName}}</template>
            </el-input>
            <span v-if="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'">{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
            <el-input v-else
                      @input.native="crud.inuptCount(scope, 'mainNum',taxAmountChangeFeeAmount)"
                      v-model="scope.row.mainNum"
                      style="width: 45%!important;">
              <template slot="append" >{{scope.row.mainUnitName}}</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('feeAmount')" prop="feeAmount" label="费用金额">
          <template slot-scope="scope">
            <el-input-number
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              style="width:100%"
              v-model="scope.row.feeAmount"
              :precision="2"
              :step="0.1"
              @change="changeFeeAmount(scope,$event)"
            />
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('supplierAmount')" prop="supplierAmount" label="供应商费用">
          <template slot-scope="{row}">
            <el-input-number
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              style="width:100%"
              v-model="row.supplierAmount"
              :precision="2"
              :step="0.1"
              @change="changeSupplierAmount(row,$event)"
            />
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('ownAmount')" prop="ownAmount" label="自理费用">
          <template slot-scope="{row}">
            <el-input-number
              :disabled="true"
              style="width:100%"
              v-model="row.ownAmount"
              :precision="2"
              :step="0.1"
              @change="changeOwnAmount"
            />
          </template>
        </el-table-column>
        <el-table-column width="200" v-if="columns.visible('remark')" prop="remark" label="备注">
          <template slot-scope="{row}">
            <el-input v-model="row.remark" style="width: 100%;"></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              slot="reference" class="el-icon-delete opration_icon_btn"
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              style="border: none;width: auto;height: auto"
              @click="delAddRow(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="feeOrder"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.detailedPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </el-dialog>
    <el-dialog title="" :visible.sync="showPayBack" width="40%">
      <el-form ref="payBackForm" size="small" label-width="90px" :model="payBack" :rules="payRules">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="业务日期" prop="busDate">
              <el-date-picker
                v-model="payBack.busDate"
                type="date"
                style="width: 100%;"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="支付银行" prop="bankId">
              <zSelect :value.sync="payBack.bankId"
                       :showName="payBack.bankName"
                       url="api/basBank/getBasBanksById"
                       :labelKey="'bankName'"
                       :params="{sort: 'seq desc'}"
                       :valueKey="'bankId'"
                       style="width:  100%;"
                       @change="bankSelectFunc"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input type="text" disabled="true" v-model="payBack.bankAccount"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="银行支行" prop="bankOpenBranch">
              <el-input type="text" disabled="true" v-model="payBack.bankOpenBranch"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="支付金额" prop="taxAmount">
              <el-input-number
                style="width:100%"
                v-model="payBack.taxAmount"
                :precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="payBack.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="showPayBack = false">取消</el-button>
        <el-button :loading="loadingPayBack" type="primary" @click="payConfirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudFeeOrder from '@/api/erp/feeOrder'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import ElSelectTree from 'el-select-tree'
import {getTree} from "@/api/erp/basSubject";
import {getNowTime, isEmpty} from "@/utils";
import {Notification} from "element-ui";
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import crudFeePay from "@/api/erp/feePay";
import crudFeeBack from "@/api/erp/feeBack";
import jtgSelectPlus from '../../../components/select/JtgSelectPlus.vue'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '费用单明细',
  url: 'api/feeOrder/detail',
  sort: 'id,desc',
  params() {
    const href = location.href.split('/')
    if (href[5].includes('copyId')) {
      return {
        id: href[5].replace("copyId=", ""),
      }
    } else {
      return {
        id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1], page: 0, size: 999,
      }
    }
  },
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: false,
    downloadDetail: false,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    print: true,
    printDetail: true
  },
  order: {
    busDate: getNowTime(),
    detailList: []
  },
  crudMethod: {...crudFeeOrder}
})
const defaultForm = {
  id: null,
  orderId: null,
  inStartDate: null,
  useEndDate: null,
  feeAmount: null,
  supplierRate: null,
  supplierAmount: null,
  ownRate: null,
  ownAmount: null,
  seq: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  settleType:1
}
export default {
  name: 'feeOrderDetail',
  components: {pagination, crudOperation, rrOperation, udOperation, ElSelectTree, jPrintConfig, jtgSelectPlus},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_fee_order_type', 'common_yes_or_no'],
  data() {
    return {
      nowTime: getNowTime(),
      permission: {
        add: ['admin', 'feeOrderDetail:add'],
        edit: ['admin', 'feeOrderDetail:edit'],
        del: ['admin', 'feeOrderDetail:del'],
        import: ['admin', 'feeOrderDetail:import'],
        export: ['admin', 'feeOrderDetail:export'],
        copy: ['admin', 'feeOrderDetail:copy'],
        upload: ['admin', 'feeOrderDetail:upload'],
        download: ['admin', 'feeOrderDetail:download'],
      },
      settleTypeList:[
        {label:'现金',value:1},
        {label:'产品',value:2},
      ],
      rules: {
        // name: [
        //   {required: true, message: '合同名称不能为空', trigger: 'blur'}
        // ],
        type: [
          {required: true, message: '费用类型不能为空', trigger: 'blur'}
        ],
        feeAmount: [
          {required: true, message: '费用金额不能为空', trigger: 'blur'}
        ],
        supplierAmount: [
          {required: true, message: '供应商费用不能为空', trigger: 'blur'}
        ],
        ownAmount: [
          {required: true, message: '自理费用不能为空', trigger: 'blur'}
        ],
        startDate: [
          {required: true, message: '生效开始时间不能为空', trigger: 'blur'}
        ],
        endDate: [
          {required: true, message: '生效截止时间不能为空', trigger: 'blur'}
        ],
      },
      payRules: {
        busDate: [
          {required: true, message: '业务日期不能为空', trigger: 'blur'}
        ],
        bankId: [
          {required: true, message: '支付银行不能为空', trigger: 'blur'}
        ],
        taxAmount: [
          {required: true, message: '支付金额不能为空', trigger: 'blur'}
        ],
      },
      selection: [],
      able: false,
      enable: false,
      subjects: [],
      payBack: {
        id: null,
        flag: null,
        busDate: getNowTime(),
        remark:null,
        taxAmount:this.crud.order.feeAmount
      },
      showPayBack: false,
      loadingPayBack:false,
    }
  },
  activated() {
    //获取上次进入Id
    const id = sessionStorage.getItem(this.$options.name + 'Id')
    //记录本次进入的Id
    sessionStorage.setItem(this.$options.name + 'Id', this.$route.params.id)
    if (id !== this.$route.params.id) {
      if (this.$route.params.id === 'add') {
        if (this.crud.getItemInfo("feeOrderDetail_add")) {
          return false
        }
        this.crud.order = {
          busDate: getNowTime(),
          detailList: []
        }
      }else {
        this.crud.params.id = this.$route.params.id
        this.crud.refresh()
      }
    }

    this.idDate = this.$route.query.idDate
    if (this.idDate) {
      this.idList = JSON.parse(sessionStorage.getItem(this.idDate)) || []
    } else {
      this.idList = []
    }
    this.isExceed = this.$route.query.isExceed
  },
  watch: {},
  destroyed() {
    this.crud.setItemInfo("feeOrderDetail_add")
  },
  created() {
    this.getSubjects()
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    [CRUD.HOOK.afterRefresh](crud, form) {
      if (!crud.order.detailList) {
        crud.order.detailList = []
      }
      if (isEmpty(crud.order.busDate)) {
        crud.order.busDate = getNowTime()
      }
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.orderStatus = 'SAVE'
        const list = ['audit','update','close','create','cancel']
        let i
        while (i = list.pop()){
          this.crud.order[`${i}UserId`] = null
          this.crud.order[`${i}UserName`]= null
          this.crud.order[`${i}UserCode`] = null
          this.crud.order[`${i}Time`] = null
          this.crud.order[`${i}Date`] = null
        }
      }
    },
    submit() {
      this.$refs['orderForm'].validate(valid => {
        if (!valid) {
          return
        }
        if (this.crud.order.type === 1 && (isEmpty(this.crud.order.supplierId) || this.crud.order.supplierId === 0)) {
          Notification.error({title: "供应商不能为空，请检查"})
          return;
        }
        if (this.crud.order.type === 2 && (isEmpty(this.crud.order.customerId) || this.crud.order.customerId === 0)) {
          Notification.error({title: "客户不能为空，请检查"})
          return;
        }
        var oDate1 = new Date(this.crud.order.startDate);
        var oDate2 = new Date(this.crud.order.endDate);
        if (oDate1.getTime() > oDate2.getTime()) {
          this.$message({
            message: '生效开始时间不能大于生效结束时间',
            type: 'warning'
          })
          return
        }
        this.save()
      })
    },
    changeGoods(goods,row){
      Object.assign(row,goods);
    },
    taxAmountChangeFeeAmount(row){
      row.feeAmount = row.taxAmount
    },
    //保存
    save() {
      let that = this
      let params = this.crud.order
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.id = 0
        this.crud.order.sourceType = '1'
        this.crud.order.sourceId = 0
        this.crud.order.sourceCode = null
        for (let i = 0; i <this.crud.order.detailList.length; i++) {
          this.crud.order.detailList[i].id = null
          this.crud.order.detailList[i].orderId = null
        }
      }
      if (this.crud.order.orderStatus !== 'SAVE'){
        params.isEditWithoutReject = 1
      }
      crudFeeOrder.add(params).then(res => {
        if (res.success) {
          this.crud.order = res.data.order
          let id = this.crud.order.id
          if (this.$route.params.id == 'add' || href[5].includes('copyId')) {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({params: {id}})
            this.crud.cleanItemInfo("feeOrderDetail_add")
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.loadingClose()
        } else {
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res) => {
        that.crud.loadingClose()
      })
    },
    addRow() {
      const item = {
        feeAmount:0,
        supplierAmount:0,
        ownAmount:0,
        goodsId:0,
        goodsName:'',
        taxPrice:0,
        taxBoxPrice:0,
        taxAmount: 0,
        goodsCount: 0
      }
      this.crud.order.detailList.push(item)
    },
    delAddRow(i) {
      if (this.$route.params.id !== 'add') {
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.order.detailList.splice(i, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.crud.order.detailList.splice(i, 1)
      }
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    copyRow() {
      for (let i = 0; i < this.selection.length; i++) {
        this.crud.order.detailList.push(this.selection[i])
      }
    },
    changeSubjects(e, row) {
      row.subjectCode = e.code
      row.subjectName = e.name
    },
    getSubjects() {
      getTree().then(res => {
        this.subjects = []
        const subjects = {id: 0, name: '顶级分类', children: []}
        subjects.children = res.data
        this.subjects.push(subjects)
      })
    },
    changesupplier(){
      let rate=this.crud.order
      rate.supplierRate=parseFloat(rate.supplierRate).toFixed(2)
      if(rate.supplierRate>100){
        rate.supplierRate=100
        rate.supplierAmount=rate.feeAmount
      }else if(rate.supplierRate<0){
        rate.supplierRate=0
        rate.supplierAmount=0
      }
      rate.ownRate=(100-rate.supplierRate).toFixed(2)
      rate.supplierAmount=(rate.feeAmount*(rate.supplierRate/100)).toFixed(2)
      rate.ownAmount=(rate.feeAmount*(1-rate.supplierRate/100)).toFixed(2)
    },
    changeFeeAmount(scope, e) {
      if(isEmpty(scope.row.supplierAmount)){
        scope.row.supplierAmount = e
        this.changeSupplierAmount(scope.row,e)
      }
      this.crud.order.feeAmount = 0.00
      for (let i = 0; i < this.crud.order.detailList.length; i++) {
        this.crud.order.feeAmount += this.crud.order.detailList[i].feeAmount
      }
      scope.row.ownAmount = scope.row.feeAmount - scope.row.supplierAmount
      this.changeOwnAmount()
      if(crud.order.settleType === 2 && scope.row.goodsId){
        this.crud.inuptCount(scope, 'taxAmount',this.taxAmountChangeFeeAmount)
      }

    },
    changeSupplierAmount(row, e) {
      this.crud.order.supplierAmount = 0.00
      for (let i = 0; i < this.crud.order.detailList.length; i++) {
        this.crud.order.supplierAmount += this.crud.order.detailList[i].supplierAmount
      }
      row.ownAmount = row.feeAmount - row.supplierAmount
      this.changeOwnAmount()
    },
    changeOwnAmount(e) {
      this.crud.order.ownAmount = 0.00
      for (let i = 0; i < this.crud.order.detailList.length; i++) {
        this.crud.order.ownAmount += this.crud.order.detailList[i].ownAmount
      }
    },
    changeSupplier(e) {
      this.crud.order.supplierId = e.id
      this.crud.order.supplierName = e.name
    },
    changeCustomer(e) {
      this.crud.order.customerId = e.id
      this.crud.order.customerName = e.name
    },
    changeBrand(row, e) {
      row.goodsBrandCode = e.code
      row.goodsBrandName = e.name
    },
    doPay(flag, type, id) {
      this.payBack.flag = flag
      this.payBack.id = id
      this.payBack.taxAmount = this.crud.order.feeAmount
      if(flag === 'back' && type === 3) this.payBack.taxAmount = this.crud.order.supplierAmount
      this.showPayBack = true
    },
    bankSelectFunc(selectedBank) {
      const {id, name, bankOpenBranch, bankAccount, balanceAmount, remark} = selectedBank;
      this.payBack.bankId = id
      this.payBack.bankName = name
      this.payBack.bankOpenBranch = bankOpenBranch
      this.payBack.bankAccount = bankAccount
      this.payBack.balanceAmount = balanceAmount
      this.payBack.remark = remark
    },
    payConfirm() {
      this.$refs['payBackForm'].validate(valid => {
        if (!valid) {
          return
        }
        if (this.crud.order.type !== 3 && this.crud.order.feeAmount !== this.payBack.taxAmount) {
          this.$message.warning("支付金额必须等于费用金额")
          return;
        }
        let that = this
        let feePayBankDtos = []
        let bankItem = {
          bankId: this.payBack.bankId,
          bankName: this.payBack.bankName,
          bankCode: this.payBack.bankCode,
          bankOpenBranch: this.payBack.bankOpenBranch,
          bankAccount: this.payBack.bankAccount,
          taxAmount: this.payBack.taxAmount,
          remark: this.payBack.remark
        }
        feePayBankDtos.push(bankItem)
        // let customerId = null
        // let customerName = null
        // let customerCode = null
        // if (this.crud.order.supplierId === null || this.crud.order.supplierId === 0) {
        //   customerId = this.crud.order.customerId
        //   customerName = this.crud.order.customerName
        //   customerCode = this.crud.order.customerCode
        // } else {
        //   customerId = this.crud.order.supplierId
        //   customerName = this.crud.order.supplierName
        //   customerCode = this.crud.order.supplierCode
        // }
        if (this.payBack.flag === 'pay') {
          let orderDetail = []
          let item = {
            busDate: this.payBack.busDate,
            sourceType:this.crud.order.type !== 3 ? '1' : '8',
            sourceId:this.crud.order.id,
            sourceName:this.crud.order.name,
            sourceCode:this.crud.order.code,
            feeType:1,
            remark:this.crud.order.remark,
            curCancelAmount:this.payBack.taxAmount,
            customerCode:this.crud.order.customerCode,
            customerId:this.crud.order.customerId,
            customerName:this.crud.order.customerName,
            feeAmount:this.payBack.taxAmount,
            cancelAmount:this.payBack.taxAmount
          }
          orderDetail.push(item)
          let order = {
            busDate: this.crud.order.busDate,
            customerId: this.crud.order.customerId,
            customerName: this.crud.order.customerName,
            customerCode: this.crud.order.customerCode,
            deptId: this.crud.order.deptId,
            deptCode: this.crud.order.deptCode,
            deptName: this.crud.order.deptName,
            payAmount: this.payBack.taxAmount,
            type: 1,
            isFeeOrder: "feeOrder",
            remark: this.payBack.remark,
            feePayBankDtos: feePayBankDtos,
            feePayOrderDtos: orderDetail
          }
          this.loadingPayBack = true
          crudFeePay.add(order).then(res => {
            this.loadingPayBack = false
            if (res.success) {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.payBack= {
                id: null,
                flag: null,
                busDate: getNowTime(),
                remark:null,
                taxAmount:this.crud.order.feeAmount
              }
              this.showPayBack = false
            } else {
              that.crud.loadingClose()
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }

          }).catch((res) => {
            this.loadingPayBack = false
          })
        } else {
          let orderDetail = []
          let item = {
            busDate: this.payBack.busDate,
            sourceType:this.crud.order.type !== 3 ? '1' : '9',
            sourceId:this.crud.order.id,
            sourceName:this.crud.order.name,
            sourceCode:this.crud.order.code,
            feeType:1,
            remark:this.crud.order.remark,
            curCancelAmount:this.payBack.taxAmount,
            supplierCode:this.crud.order.supplierCode,
            supplierId:this.crud.order.supplierId,
            supplierName:this.crud.order.supplierName,
            feeAmount:this.payBack.taxAmount,
            cancelAmount:this.payBack.taxAmount
          }
          orderDetail.push(item)
          let order = {
            busDate: this.crud.order.busDate,
            supplierId: this.crud.order.supplierId,
            supplierName: this.crud.order.supplierName,
            supplierCode: this.crud.order.supplierCode,
            deptId: this.crud.order.deptId,
            deptCode: this.crud.order.deptCode,
            deptName: this.crud.order.deptName,
            backAmount: this.payBack.taxAmount,
            type: 1,
            isFeeOrder: "feeOrder",
            remark: this.payBack.remark,
            feeBackBankDtos: feePayBankDtos,
            feeBackOrderDtos: orderDetail
          }
          this.loadingPayBack = true
          crudFeeBack.add(order).then(res => {
            this.loadingPayBack = false
            if (res.success) {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.showPayBack = false
            } else {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }

          }).catch((res) => {
            this.loadingPayBack = false
          })
        }

      })
    },
    copyOrder() {
      if(isEmpty(this.crud.order.id) || this.crud.order.id === 0){
        this.$message.error("请保存后再复制")
        return
      }
      this.$router.replace({path: `/redirect/fee/feeOrderDetail/copyId=${this.crud.order.id}`})
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
